import { store } from "../index";
import { defineStore } from "pinia";
import storage from "@/utils/storage";
import { resetRouter } from "@/router";
interface userState {
  token: undefined | string;
  userInfo: UserInfoFace | undefined;
}
import { info } from "@/api/user";
export const useUserStore = defineStore("user", {
  state: (): userState => {
    return {
      token: storage.get("token", false) as undefined | string,
      userInfo: storage.get("user", true) as undefined | UserInfoFace, // 如果采用判断UserInfoFace是否存在来进行路由监听就不要缓存 user了
    };
  },
  getters: {
    // 获取token
    getToken(): undefined | string {
      return this.token;
    },
    getUser(): UserInfoFace | undefined {
      return this.userInfo;
    },
  },
  actions: {
    setToken(token: string | undefined) {
      storage.set("token", token);
      this.token = token;
    },
    setUser(user: UserInfoFace | undefined) {
      storage.set("user", user);
      this.userInfo = user;
    },
    getuserInfo(): Promise<UserInfoFace> {
      return new Promise((resolve, reject) => {
        this.setUser({
          member_id: 1,
        });
        resolve({ member_id: 1 });
        // 登录
        return false;
        info()
          .then((res) => {
            this.setUser(res.data);
            resolve(res.data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    loginOut() {
      this.setToken(undefined);
      this.setUser(undefined);
      resetRouter();
    },
  },
});
// 如果需要初始化时执行，则可以采用此方法
export const useUserStoreWithOut = () => {
  return useUserStore(store);
};
